package cn.edu.hit.core.transfer;

import cn.edu.hit.core.Document;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.edu.hit.core.combine.CombineAdapter.FEATURE_ID;
import static cn.edu.hit.core.combine.CombineAdapter.TRANSFER_ARG;

public class HistoryTransfer implements Transfer<List, List, Document> {
    protected int getDefaultPoolSize() {
        return 2;
    }

    /**
     * @param source    通道组
     * @param configure 配置行数据
     * @return
     */
    @Override
    public List transfer(List source, Document configure) {
        String id = configure.getString(FEATURE_ID);
        String transferArg = configure.getString(TRANSFER_ARG);

        int poolSize = getDefaultPoolSize();
        try {
            poolSize = Integer.parseInt(transferArg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        poolSize = poolSize < getDefaultPoolSize() ? getDefaultPoolSize() : poolSize;

        Queue queue;
        if (pool.containsKey(id)) {
            queue = pool.get(id);
        } else {
            queue = new ArrayDeque();
        }

        source.forEach(l -> {
            if (l instanceof List) {
                queue.addAll((List) l);
            } else {
                queue.add(l);
            }
        });

        while (queue.size() > poolSize) {
            queue.poll();
        }

        pool.put(id, queue);

        Stream<Object> resultStream = queue.stream();
        List resultList = resultStream.collect(Collectors.toList());
//        System.out.println(resultList);
        return resultList;
    }

    @Override
    public boolean accept(String name) {
        return "History".equalsIgnoreCase(name);
    }

    protected Map<String, Queue> pool = new HashMap<>();
}
